package edu.gyc.swing.test;

import javax.swing.*;
import javax.swing.filechooser.FileNameExtensionFilter;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.io.FilenameFilter;
import java.util.List;
import java.util.Timer;
import java.util.*;

public class HiPic4 extends JFrame {
    public static final int WIDTH = 800;
    public static final int HEIGHT = 600;
    private JFileChooser fileChooser = new JFileChooser();
    //存放目标目录里图片文件的真实路径
    private List<String> picFilePaths = new ArrayList<>();
    private String currentPicPath;
    private JButton previousBt, nextBt;
    private JButton openBt, carouselBt;
    private JPanel menuPanel;
    //图片显示的载体，和状态栏
    private JPanel picPanel;
    private JLabel picLabel, statusLabel;
    private int count = 0;
    private Timer timer;
    public static String filePath = "K:" + System.getProperty("file.separator") + "girls";//默认只能打开的跟路径

    public HiPic4() {
        super("PhotoViewer");
        setSize(WIDTH, HEIGHT);
        menuPanel = new JPanel();
        openBt = new JButton("Open");
        menuPanel.add(openBt);
        carouselBt = new JButton("幻灯播放");
        menuPanel.add(carouselBt);
        getContentPane().add(menuPanel, BorderLayout.NORTH);
        this.addMouseListener(new MyMouseListener());
        fileChooser.setCurrentDirectory(new File(filePath));
        //文件名过滤器，让fileChooser只显示目录类指定类型的文件
        FileNameExtensionFilter fileNameExtensionFilter = new FileNameExtensionFilter("ImageFiles", "jpg"
                , "jpeg");
        fileChooser.setFileFilter(fileNameExtensionFilter);
        openBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                fileChooser.setCurrentDirectory(new File(filePath));
                int result = fileChooser.showOpenDialog(null);
                if (result == JFileChooser.APPROVE_OPTION) {
                    //用户选中了图片文件地址
                    currentPicPath = fileChooser.getSelectedFile().getAbsolutePath();
                    //获取选中图片的目录地址
                    String picDir = fileChooser.getSelectedFile().getParent();
                    //显示图片
                    scalePic(currentPicPath);
                    //开启一个线程搜索指定目录下所有图片地址放置在picFilePaths中
                    asyncGetPicPath(picDir);
                    picPanel.requestFocus();
                }

            }
        });

        carouselBt.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e) {
                timer = new Timer();
                timer.schedule(new TimerTask() {
                    @Override
                    public void run() {
                        count++;
                        if (count >= picFilePaths.size()) {
                            count = 0;
                        }
                        scalePic(picFilePaths.get(count));
                    }
                }, 0, 3000);
                //让picLabel获取焦点，响应keyListener
                picPanel.requestFocus();
                //幻灯播放时，menuPanel应隐藏以增加显示空间，按键按下显示菜单栏
                carouselBt.setEnabled(false);
                menuPanel.setVisible(false);

            }
        });

        picPanel = new JPanel();
        picPanel.addKeyListener(new HiKeyListener());

        picLabel = new JLabel();
        picPanel.setLayout(new BorderLayout());
        picPanel.add(picLabel, BorderLayout.CENTER);

        getContentPane().add(picPanel, BorderLayout.CENTER);
        statusLabel = new JLabel("当前文件是：");
        getContentPane().add(statusLabel, BorderLayout.SOUTH);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setLocationRelativeTo(null);
        setVisible(true);

    }



    private void scalePic(String path) {
        ImageIcon icon = new ImageIcon(path);
        //等比缩放条件
        int imgWidth = icon.getIconWidth();
        int imgHeight = icon.getIconHeight();
        System.out.println("imgWidth: " + imgWidth + " imgHeight:" + imgHeight);
        int targetWidth = picPanel.getWidth();
        int targetHeight = picPanel.getHeight();
        System.out.println("targetWidth: " + targetWidth + " targetHeight:" + targetHeight);
        int reImgWidth = 0;
        int reImgHeight = 0;
        float resize = 0;
        float resize1 = 0;
        float resize2 = 0;
        resize1 = (float) (targetHeight * 1.0 / imgHeight);
        resize2 = (float) (targetWidth * 1.0 / imgWidth);
        if (resize1 > resize2) {
            resize = resize2;
        } else {
            resize = resize1;
        }
        System.out.println("resize: " + resize);
        if (resize >= 1) { //小图片就原样输出
            reImgWidth = imgWidth;
            reImgHeight = imgHeight;
        } else {
            reImgWidth = (int) (imgWidth * resize);
            reImgHeight = (int) (imgHeight * resize);
        }
        System.out.println("reImgWidth " + reImgWidth + " reImgHeight" + reImgHeight);
        //这个是按等比缩放
        icon = new ImageIcon(icon.getImage().getScaledInstance(reImgWidth, reImgHeight, Image.SCALE_SMOOTH));

        picLabel.setIcon(icon);
        picLabel.setHorizontalAlignment(SwingConstants.CENTER);
        String s = "当前文件：" + path + " widht:" + imgWidth + " height:" + imgHeight;
        if (!menuPanel.isVisible()) {
            this.setTitle("PhotoViewer " + s);
            statusLabel.setVisible(false);

        } else {
            statusLabel.setText(s);
        }
    }

    class HiKeyListener implements KeyListener {

        @Override
        public void keyTyped(KeyEvent e) {

        }

        @Override
        public void keyPressed(KeyEvent e) {
            handlerMouseKey();

            switch (e.getKeyCode()) {
                case KeyEvent.VK_LEFT:
                    count--;
                    if (count < 0) {
                        count = picFilePaths.size() - 1;
                    }
                    scalePic(picFilePaths.get(count));
                    break;
                case KeyEvent.VK_RIGHT:
                    count++;
                    if (count >= picFilePaths.size()) {
                        count = 0;
                    }
                    scalePic(picFilePaths.get(count));
                    break;
            }
        }

        @Override
        public void keyReleased(KeyEvent e) {

        }
    }

    private void handlerMouseKey() {

        if (timer != null) {
            timer.cancel();
        }
        //按下键盘就显示菜单
        menuPanel.setVisible(true);
        carouselBt.setEnabled(true);
        statusLabel.setVisible(true);
    }

    class MyMouseListener implements MouseListener {

        @Override
        public void mouseClicked(MouseEvent e) {

        }

        @Override
        public void mousePressed(MouseEvent e) {
            handlerMouseKey();
        }

        @Override
        public void mouseReleased(MouseEvent e) {

        }

        @Override
        public void mouseEntered(MouseEvent e) {

        }

        @Override
        public void mouseExited(MouseEvent e) {

        }
    }

    public void getDirPicPath(String dir) {
        File file = new File(dir);
        if (!file.exists()) {
            JOptionPane.showMessageDialog(null, dir + " 路径不存在！");
        }
        String[] fileNames = file.list(new FilenameFilter() {
            @Override
            public boolean accept(File dir, String name) {
                if (name.endsWith("jpg") || name.endsWith("jpeg")) {
                    return true;
                }
                return false;
            }
        });

        picFilePaths.addAll(Arrays.asList(fileNames));
        System.out.println(picFilePaths);
        //  Collections.sort(picFilePaths);//字符串排序
        //按数字大小排序
        Collections.sort(picFilePaths, new Comparator<String>() {
            @Override
            public int compare(String o1, String o2) {
                if (o1.length() <= 5 && o2.length() <= 5) {
                    o1 = rename(o1);
                    o2 = rename(o2);
                }


                return o1.compareTo(o2);
            }
        });
        System.out.println(picFilePaths);
        for (int i = 0; i < picFilePaths.size(); i++) {
            String s = picFilePaths.get(i);
            s = dir + File.separator + s;
            picFilePaths.set(i, s);
        }
        System.out.println(picFilePaths);


    }

    private static int extractNumber(String name) {
        int i;
        try {
            String number = name.replaceAll("[^\\d]", "");
            i = Integer.parseInt(number);
        } catch (Exception e) {
            i = 0;
        }
        return i;
    }
//数字文件名规格化，1.jpg——》00001.jpg，方便字符串排序
    private String  rename(String name) {
        String str = "00000";

            String pre=name.substring(0,name.indexOf("."));
            String sub = name.substring(name.indexOf("."));
        System.out.println(pre +" "+sub);
            name=str.substring(0,5-pre.length())+pre+sub;
            System.out.println(name);

        return name;
    }

    private void asyncGetPicPath(String path) {
        picFilePaths.clear();
        new Thread(new Runnable() {
            @Override
            public void run() {
                getDirPicPath(path);
                JOptionPane.showMessageDialog(null, path + "目录文件检索完毕，共有图片" + picFilePaths.size());
                if (picFilePaths.size() > 0) {
                    String path = picFilePaths.get(0);
                }
            }
        }).start();
    }

    public static void main(String[] args) {
        HiPic4 hiPic = new HiPic4();
    }


}

